import { Modal, Table, TableProps } from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import style from "./index.module.scss"
import { dataStore, orderCountStore } from '@/store'
import { generatePerson, getAssetPath } from '@/utils'
const columns: TableProps['columns'] = [
    {
        title: "报备人",
        dataIndex: "bbr",
        align: "center",
    },
    {
        title: "公司",
        dataIndex: "bm",
        align: "center",
    },
    {
        title: "物料名称",
        dataIndex: "orderName",
        align: "center",
    },
    {
        title: "地区",
        dataIndex: "dir",
        align: "center",
    },
    {
        title: "省份",
        dataIndex: "area",
        align: "center",
    },
]
// const bbrArry = generatePerson().map(v => v.xm)
const bbrArry = generatePerson()
console.log(bbrArry);
const getRandomTime = () => {
    const min = 180000; // 3分钟（毫秒）
    const max = 600000; // 10分钟（毫秒）
    return Math.floor(Math.random() * (max - min + 1)) + min;
};
const ModalOrder: React.FC = () => {
    function toData() {

        const res = bbrArry[Math.floor(Math.random() * bbrArry.length)]

        return [
            {
                id: 1,
                bbr: res.xm,
                orderName: res.goods,
                bm: res.bm,
                dir: res.dir,
                area: res.area
            }
        ]
    }
    const [dataSource, setDataSource] = useState(toData)
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [countdown, setCountdown] = useState(5); // 5秒倒计时
    const showTimerRef = useRef<NodeJS.Timeout | null>(null);
    const countdownIntervalRef = useRef<NodeJS.Timeout | null>(null);
    const { updateDataArray } = dataStore()
    const { updateOrderCount } = orderCountStore()

    function peoImg() {
        const name = generatePerson().find(v => v.xm === dataSource[0].bbr)?.dataIndex
        return getAssetPath(`${name}.png`)
    }
    // 控制倒计时
    useEffect(() => {
        if (isModalVisible) {
            const newDataSource = toData()
            setDataSource(newDataSource)
            updateDataArray(preVal => preVal.map(v => {
                if (v.xm === newDataSource[0].bbr) {
                    return {
                        ...v,
                        bbzs: v.bbzs + 1,
                        zzgj: v.zzgj + 1
                    }
                } else {
                    return v
                }
            }))
            updateOrderCount(preVal => preVal.map(v => {
                if (v.title === "全球报备总数合计") {
                    return {
                        ...v,
                        value: v.value! + 1
                    }
                } else {
                    return v
                }
            }))
            countdownIntervalRef.current = setInterval(() => {
                setCountdown((prev) => {
                    if (prev <= 1) {
                        handleCloseModal();
                        return 5; // 关闭后重置倒计时
                    }
                    return prev - 1;
                });
            }, 1000);
        } else {
            if (countdownIntervalRef.current) clearInterval(countdownIntervalRef.current);
            const randomTime = getRandomTime();
            showTimerRef.current = setTimeout(() => {
                setIsModalVisible(true);
                setCountdown(5); // 重新初始化倒计时
            }, randomTime);
        }
        return () => {
            if (countdownIntervalRef.current) clearInterval(countdownIntervalRef.current);
        };
    }, [isModalVisible, updateOrderCount, updateDataArray]);

    // 关闭 `Modal` 并重启 `20s` 计时
    const handleCloseModal = () => {
        setIsModalVisible(false);
    };
    return (
        <Modal title="当日报备新增提示" className={`${style["custome-module"]}`} open={isModalVisible}
            onCancel={handleCloseModal} footer={false}>
            <div className='flex flex-1'>
                <div className='text-amber-50 absolute top-[9%] right-[8%] tracking-[2px]'>{countdown}s后关闭</div>
                <img src={peoImg()} alt="" className='w-[80px] mr-[30px]' />
                <Table size="small" columns={columns} pagination={false} dataSource={dataSource} rowKey="id" />
            </div>
        </Modal>
    )
}

export default ModalOrder